/*
    echo_server.c
        Achieve the echo server
    BeginnerC
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define DEFAULT_BUFFER_SIZE 2048
int main(int argc, char *argv[])
{
    int server_fd = 0;
    int buffer_size = DEFAULT_BUFFER_SIZE;
    char *buffer = NULL;
    struct sockaddr_in address = {};
    if (argc != 2 && argc != 3)
    { 
        puts("Usage: EchoServer <port> [<buffer size>]");
        return 0;
    }
    if (3 == argc)
    {
        buffer_size = atoi(argv[2]);
    }
    buffer = (char*)calloc(buffer_size, sizeof(char));
    if (NULL == buffer)
    {
        puts("Error: alloc memory failed");
        return -1;
    }
    server_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (server_fd < 0)
    {
        puts("Error: socket failed");
        return -1;
    }
    address.sin_family = AF_INET;
    address.sin_port = htons(atoi(argv[1]));-
    address.sin_addr.s_addr = htonl(INADDR_ANY);
    bind(server_fd, (const struct sockaddr *)&address, sizeof(address));
    listen(server_fd, 1);
    while (1)
    {
        int connect_fd = 0;
        connect_fd = accept(server_fd, NULL, 0);
        while (1)
        {
            memset(buffer, 0, buffer_size);
            read(connect_fd, buffer, buffer_size);
            if (!strcmp(buffer, "Q\n") || !strcmp(buffer, "Q") || !strcmp(buffer, "Q\r\n"))
            {
                break;
            }
            write(connect_fd, buffer, buffer_size);
        }
        close(connect_fd);
    }
    free(buffer);
    return 0;
}
